<template>
  <div class="list-common-table">
    <div class="today-use-count" v-if="todaySummaryData">
      <span style="margin-right: 50px" v-if="sessionType === 1"
        >当日晨练消费人次： {{ todaySummaryData.forenoonConsumer }}</span
      >
      <span style="margin-right: 50px" v-if="sessionType === 2"
        >当日午场消费人次： {{ todaySummaryData.afternoonConsumer }}</span
      >
      <span style="margin-right: 50px" v-if="sessionType === 3"
        >当日晚场消费人次： {{ todaySummaryData.nightConsumer }}</span
      >
    </div>
    <t-form ref="form" :data="formData" :label-width="0" colon @reset="onReset" @submit="onSubmit">
      <t-row>
        <t-col :span="12">
          <t-row :gutter="[15, 15]">
            <t-col :span="2">
              <t-form-item name="userName">
                <t-input
                  v-model="formData.userName"
                  class="form-item-content"
                  type="search"
                  :placeholder="$t('pages.memberBase.memberBaseSearch.memberNamePlaceholder')"
                  :style="{ minWidth: '120px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :span="2">
              <t-form-item name="mobilePhone">
                <t-input
                  v-model="formData.mobilePhone"
                  class="form-item-content"
                  :placeholder="$t('pages.memberBase.memberBaseSearch.memberPhonePlaceholder')"
                  :style="{ minWidth: '120px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :span="2">
              <t-form-item name="gtConsumerCount">
                <t-select
                  v-model="formData.level"
                  class="form-item-content"
                  :options="USERLEVEL_OPTIONS"
                  :style="{ minWidth: '120px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :span="2" class="operation-container">
              <t-button theme="primary" type="submit" :style="{ marginLeft: 'var(--td-comp-margin-s)' }">
                {{ $t('components.commonTable.query') }}
              </t-button>
              <t-button type="reset" variant="base" theme="default">
                {{ $t('components.commonTable.reset') }}
              </t-button>
            </t-col>
          </t-row>
        </t-col>
      </t-row>
    </t-form>

    <div class="table-container">
      <t-table
        :data="data"
        :columns="COLUMNS"
        :row-key="rowKey"
        :vertical-align="verticalAlign"
        :pagination="pagination"
        :loading="dataLoading"
        :header-affixed-top="headerAffixedTop"
        :stripe="true"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
      >
        <template #userName="{ row }">
          <span v-if="row.level === 0" style="color: red">{{ row.userName }}</span>
          <span v-if="row.level === 1">{{ row.userName }}</span>
          <span v-if="row.level === 2" style="color: green">{{ row.userName }}</span>
        </template>
        <template #remainingNum="{ row }">
          <span v-if="row.remainingNum < 10" style="color: red; font-weight: bold">{{ row.remainingNum }}</span>
          <span v-else style="color: green; font-weight: 500">{{ row.remainingNum }}</span>
        </template>
      </t-table>
    </div>
  </div>
</template>
<script setup lang="ts">
import { PageInfo, PrimaryTableCol, TableRowData } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

import { getMemberList, getUserTodaySummary } from '@/api/member';
import { UserTodaySummaryData } from '@/api/model/memberModel';
import { prefix } from '@/config/global';
import { useSettingStore } from '@/store';

const store = useSettingStore();
const route = useRoute();

const USERLEVEL_OPTIONS = [
  { value: '', label: '全部' },
  { value: '1', label: '会员' },
  { value: '0', label: '线下缴费' },
  { value: '2', label: '美团缴费' },
];

const COLUMNS: PrimaryTableCol[] = [
  {
    title: '序号',
    fixed: 'left',
    width: 60,
    ellipsis: true,
    align: 'left',
    colKey: 'serial-number',
  },
  {
    title: '姓名',
    fixed: 'left',
    width: 120,
    ellipsis: true,
    align: 'left',
    colKey: 'userName',
  },
  { title: '手机号', colKey: 'mobilePhone', width: 160 },
  {
    title: '充值次数',
    width: 100,
    ellipsis: true,
    colKey: 'payCount',
  },
  {
    title: '剩余次数',
    width: 100,
    ellipsis: true,
    colKey: 'remainderCount',
  },
  {
    title: '当日划卡次数',
    width: 120,
    ellipsis: true,
    colKey: 'todayUseCount',
  },
  {
    title: '最近充值日期',
    width: 200,
    ellipsis: true,
    colKey: 'lastPayTime',
  },
  {
    title: '加入时间',
    width: 200,
    ellipsis: true,
    colKey: 'registerTime',
  },
];

const formData = ref({
  userName: '',
  mobilePhone: '',
  gtConsumerCount: '',
  todayConsumer: 1,
  level: '',
});

const rowKey = 'index';
const verticalAlign = 'top' as const;

interface PagenationDTO {
  defaultPageSize?: number;
  total: number;
  defaultCurrent?: number;
  current: number;
  page: number;
  pageSize?: number;
}
const pagination = ref<PagenationDTO>({
  defaultPageSize: 50,
  total: 100,
  defaultCurrent: 1,
  current: 1,
  page: 1,
  pageSize: 50,
});

const data = ref([]);

const dataLoading = ref(false);
const fetchData = async () => {
  dataLoading.value = true;
  try {
    const res = await getMemberList({
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      cardType: sessionType.value,
      ...formData.value,
    });
    if (res.code === 0) {
      res.data.userList.map((item: { reduceCount: number }) => {
        item.reduceCount = 1;
        return item;
      });
      data.value = res.data.userList;
      pagination.value = {
        ...pagination.value,
        total: res.data.totalCount,
      };
    }
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const todaySummaryData = ref<UserTodaySummaryData>(null);
const fetchUserTodaySummary = async () => {
  const res = await getUserTodaySummary();
  if (res.code === 0) {
    todaySummaryData.value = res.data;
  }
};

const sessionType = ref<number>(Number(route.params.cardType)); // 场次类型 1-晨练 2-午场 3-晚场

onMounted(() => {
  fetchData();
  fetchUserTodaySummary();
});

const onReset = () => {
  formData.value = {
    userName: '',
    mobilePhone: '',
    gtConsumerCount: '',
    todayConsumer: 1,
    level: '',
  };
  pagination.value = {
    defaultPageSize: 50,
    total: 50,
    defaultCurrent: 1,
    current: 1,
    page: 1,
    pageSize: 50,
  };
  fetchData();
};

const onSubmit = () => {
  pagination.value = {
    defaultCurrent: 1,
    current: 1,
    page: 1,
    total: 0,
    pageSize: 50,
  };
  fetchData();
};
const rehandlePageChange = (pageInfo: PageInfo, newDataSource: TableRowData[]) => {
  console.log('分页变化', pageInfo, newDataSource);
  pagination.value = {
    ...pagination.value,
    page: pageInfo.current,
    current: pageInfo.current,
    pageSize: pageInfo.pageSize,
  };
  fetchData();
};
const rehandleChange = (changeParams: unknown, triggerAndData: unknown) => {
  console.log('统一Change', changeParams, triggerAndData);
};

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any, // TO BE FIXED
);
</script>

<style lang="less" scoped>
.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);
  border-radius: var(--td-radius-medium);

  .table-container {
    margin-top: var(--td-comp-margin-xxl);
  }
}

.form-item-content {
  width: 100%;
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .expand {
    .t-button__text {
      display: flex;
      align-items: center;
    }
  }
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}

.right-handlers-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
.user-tabs {
  margin: 10px 0;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

:deep(.t-table__pagination-wrap) {
  position: sticky;
  bottom: 0;
  background: #fff;
  z-index: 99;
  border-top: 1px solid #ddd;
}
.today-use-count {
  margin-bottom: 20px;
}
</style>
